#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WebSocket管理模块
"""

import json
import asyncio
import time
import os
from typing import Dict, List, Any, Callable, Optional
from fastapi import WebSocket

from database_manager import DatabaseManager
from config_manager import get_config


class WebSocketManager:
    """WebSocket管理器"""
    
    def __init__(self, db_manager: DatabaseManager):
        self.db_manager = db_manager
        self.connections: List[WebSocket] = []
        self.message_handlers: Dict[str, Callable] = {}
        
        # 从配置文件读取监控配置
        self.config = get_config()
        self.monitor_config = self.config.get_monitor_config()
        
        self._register_default_handlers()
    
    def add_connection(self, websocket: WebSocket):
        """添加WebSocket连接"""
        self.connections.append(websocket)
        print(f"客户端连接，当前连接数: {len(self.connections)}")
    
    def remove_connection(self, websocket: WebSocket):
        """移除WebSocket连接"""
        if websocket in self.connections:
            self.connections.remove(websocket)
        print(f"客户端断开，当前连接数: {len(self.connections)}")
    
    def register_handler(self, message_type: str, handler: Callable):
        """注册消息处理器"""
        self.message_handlers[message_type] = handler
    
    def _register_default_handlers(self):
        """注册默认消息处理器"""
        self.register_handler('ping', self._handle_ping)
        self.register_handler('get_orders', self._handle_get_orders)
        self.register_handler('create_order', self._handle_create_order)
        self.register_handler('update_order', self._handle_update_order)
        self.register_handler('delete_order', self._handle_delete_order)
        self.register_handler('start_monitoring', self._handle_start_monitoring)
        # 客户管理处理器
        self.register_handler('get_customers', self._handle_get_customers)
        self.register_handler('create_customer', self._handle_create_customer)
        self.register_handler('batch_create_customers', self._handle_batch_create_customers)
        self.register_handler('update_customer', self._handle_update_customer)
        self.register_handler('delete_customer', self._handle_delete_customer)
    
    async def handle_message(self, message: dict, websocket: WebSocket):
        """处理WebSocket消息"""
        try:
            msg_type = message.get('type')
            print(f"🔧 处理消息类型: {msg_type}")
            
            if msg_type in self.message_handlers:
                print(f"✅ 找到处理器: {msg_type}")
                await self.message_handlers[msg_type](message, websocket)
                print(f"✅ 处理器执行完成: {msg_type}")
            else:
                print(f"❌ 未知消息类型: {msg_type}")
                await self._send_error(websocket, f'未知消息类型: {msg_type}')
                
        except Exception as e:
            print(f"❌ 处理消息时发生错误: {e}")
            import traceback
            traceback.print_exc()
            await self._send_error(websocket, f'处理消息时发生错误: {str(e)}')
    
    async def _handle_ping(self, message: dict, websocket: WebSocket):
        """处理心跳消息"""
        await self._send_message(websocket, {'type': 'pong'})
    
    async def _handle_get_orders(self, message: dict, websocket: WebSocket):
        """处理获取订单消息"""
        date = message.get('date')  # 从消息中获取日期参数
        orders = self.db_manager.get_all_orders(date)
        await self._send_message(websocket, {
            'type': 'initial_data',
            'orders': orders,
            'date': date or self.db_manager.current_date
        })
    
    async def _handle_create_order(self, message: dict, websocket: WebSocket):
        """处理创建订单消息"""
        order_data = message.get('data', {})
        date = message.get('date')  # 从消息中获取日期参数
        
        # 确保文件类型有默认值
        if 'file_type' not in order_data:
            order_data['file_type'] = 'PDF'
        
        # 生成订单路径（基于当前日期和生成的编号）
        from datetime import datetime
        today = datetime.now()
        date_str = f"{today.month}.{today.day}"
        
        # 先创建订单获取生成的编号
        order = self.db_manager.create_order(order_data, date)
        order_number = order.get('number', '')
        customer = order.get('customer', '')
        
        # 生成订单路径
        order_folder_name = f"{order_number}_{customer}"
        base_path = self.monitor_config['base_path']
        order_path = os.path.join(base_path, date_str, order_folder_name)
        order['path'] = order_path
        
        # 更新数据库中的路径
        self.db_manager.update_order(order_number, {'path': order_path})
        
        # 创建订单文件夹
        try:
            os.makedirs(order_path, exist_ok=True)
            print(f"📁 创建订单文件夹: {order_path}")
            
            # 创建状态子文件夹
            status_folders = ["挂", "未确认", "已做"]
            for folder_name in status_folders:
                folder_path = os.path.join(order_path, folder_name)
                os.makedirs(folder_path, exist_ok=True)
                print(f"📁 创建状态文件夹: {folder_path}")
            
        except Exception as e:
            print(f"❌ 创建订单文件夹失败: {e}")
        
        # 为新订单添加状态数据
        from order_parser import OrderParser
        order_parser = OrderParser()
        
        # 检查订单状态
        status_data = order_parser.check_order_status(order_path)
        order['status_data'] = status_data
        print(f"📊 新订单 {order_number} 状态: {status_data}")
        
        # 广播新订单给所有客户端
        await self._broadcast_message({
            'type': 'order_created',
            
            'order': order
        })
    
    async def _handle_update_order(self, message: dict, websocket: WebSocket):
        """处理更新订单消息"""
        order_data = message.get('data', {})
        order_number = order_data.get('number')
        date = message.get('date')  # 从消息中获取日期参数
        
        if not order_number:
            await self._send_error(websocket, '缺少订单编号')
            return
        
        order = self.db_manager.update_order(order_number, order_data, date)
        if order:
            # 广播更新给所有客户端
            message = {
                'type': 'order_updated',
                'data': {
                    'order_number': order_number,
                    'order_info': order,
                    'timestamp': time.time()
                }
            }
            print(f"📤 准备广播订单更新消息: {message}")
            await self._broadcast_message(message)
        else:
            await self._send_error(websocket, '订单不存在')
    
    async def _handle_delete_order(self, message: dict, websocket: WebSocket):
        """处理删除订单消息"""
        order_number = message.get('order_number')
        date = message.get('date')  # 从消息中获取日期参数
        
        if not order_number:
            await self._send_error(websocket, '缺少订单编号')
            return
        
        success = self.db_manager.delete_order(order_number, date)
        if success:
            # 广播删除给所有客户端
            await self._broadcast_message({
                'type': 'order_deleted',
                'data': {
                    'order_number': order_number,
                    'order_info': {},  # 删除时没有订单信息
                    'timestamp': time.time()
                }
            })
        else:
            await self._send_error(websocket, '删除订单失败')
    
    async def _handle_start_monitoring(self, message: dict, websocket: WebSocket):
        """处理开始监控消息"""
        # 这个处理器需要外部监控管理器，暂时返回成功
        await self._send_message(websocket, {
            'type': 'monitoring_started',
            'message': '监控请求已接收'
        })
    
    async def send_initial_data(self, websocket: WebSocket):
        """发送初始数据"""
        orders = self.db_manager.get_all_orders()
        
        # 为每个订单添加状态数据
        from order_parser import OrderParser
        order_parser = OrderParser()
        
        for order in orders:
            order_path = order.get('path', '')
            if order_path:
                # 检查订单状态
                status_data = order_parser.check_order_status(order_path)
                order['status_data'] = status_data
                print(f"📊 订单 {order.get('number', '')} 状态: {status_data}")
        
        await self._send_message(websocket, {
            'type': 'initial_data',
            'orders': orders
        })
    
    async def broadcast_order_status_change(self, order_number: str, status_data: dict):
        """广播订单状态变化"""
        print(f"📡 准备广播订单状态变化: 订单编号 {order_number}")
        print(f"📊 状态数据: {status_data}")
        
        message = {
            'type': 'order_status_change',
            'data': {
                'order_number': order_number,
                'status': status_data,
                'timestamp': time.time()
            }
        }
        
        print(f"📤 发送消息给 {len(self.connections)} 个客户端")
        await self._broadcast_message(message)
    
    async def broadcast_order_deleted(self, order_number: str, status_data: dict):
        """广播订单删除"""
        print(f"🗑️ 准备广播订单删除: 订单编号 {order_number}")
        print(f"📊 删除数据: {status_data}")
        
        message = {
            'type': 'order_deleted',
            'data': {
                'order_number': order_number,
                'order_info': {
                    'id': status_data.get('id', ''),
                    'number': status_data.get('number', ''),
                    'customer': status_data.get('customer', ''),
                    'path': status_data.get('path', '')
                },
                'timestamp': time.time()
            }
        }
        
        print(f"📤 发送删除消息给 {len(self.connections)} 个客户端")
        await self._broadcast_message(message)
    
    async def broadcast_order_updated(self, order_number: str, order_data: dict):
        """广播订单信息更新"""
        print(f"🔄 准备广播订单信息更新: 订单编号 {order_number}")
        print(f"📝 订单数据: {order_data}")
        
        message = {
            'type': 'order_updated',
            'data': {
                'order_number': order_number,
                'order_info': order_data,
                'timestamp': time.time()
            }
        }
        
        print(f"📤 发送更新消息给 {len(self.connections)} 个客户端")
        await self._broadcast_message(message)
    
    async def broadcast_monitoring_started(self, base_path: str, date: str):
        """广播监控开始"""
        message = {
            'type': 'monitoring_started',
            'base_path': base_path,
            'date': date
        }
        await self._broadcast_message(message)
    
    async def broadcast_monitoring_stopped(self):
        """广播监控停止"""
        message = {'type': 'monitoring_stopped'}
        await self._broadcast_message(message)
    
    async def _send_message(self, websocket: WebSocket, message: dict):
        """发送消息到指定WebSocket"""
        try:
            message_str = json.dumps(message, ensure_ascii=False)
            print(f"📤 发送消息: {message.get('type', 'unknown')} (长度: {len(message_str)})")
            await websocket.send_text(message_str)
            print(f"✅ 消息发送成功: {message.get('type', 'unknown')}")
        except Exception as e:
            print(f"❌ 发送消息失败: {e}")
            import traceback
            traceback.print_exc()
    
    async def _send_error(self, websocket: WebSocket, error_message: str):
        """发送错误消息"""
        await self._send_message(websocket, {
            'type': 'error',
            'message': error_message
        })
    
    async def _broadcast_message(self, message: dict):
        """广播消息给所有连接"""
        if not self.connections:
            print("⚠️ 没有WebSocket连接，无法发送消息")
            return
        
        # 创建消息副本
        message_str = json.dumps(message, ensure_ascii=False)
        print(f"📤 广播消息: {message.get('type', 'unknown')} 给 {len(self.connections)} 个客户端")
        
        # 发送给所有连接
        disconnected = []
        success_count = 0
        
        for i, websocket in enumerate(self.connections):
            try:
                await websocket.send_text(message_str)
                success_count += 1
                print(f"✅ 消息发送成功到客户端 {i+1}")
            except Exception as e:
                # 连接已断开，标记为待移除
                print(f"❌ 发送消息到客户端 {i+1} 失败: {e}")
                disconnected.append(websocket)
        
        # 移除断开的连接
        if disconnected:
            print(f"🔌 移除 {len(disconnected)} 个断开的连接")
            for websocket in disconnected:
                self.remove_connection(websocket)
        
        print(f"📊 消息发送完成: 成功 {success_count}/{len(self.connections)}")
    
    def get_connection_count(self) -> int:
        """获取连接数"""
        return len(self.connections)
    
    def get_connections_info(self) -> List[dict]:
        """获取连接信息"""
        return [
            {
                'id': id(ws),
                'client': getattr(ws, 'client', 'unknown'),
                'state': getattr(ws, 'client_state', 'unknown')
            }
            for ws in self.connections
        ]
    
    async def close_all_connections(self):
        """关闭所有连接"""
        for websocket in self.connections.copy():
            try:
                await websocket.close()
            except Exception:
                pass
        
        self.connections.clear()
        print("所有WebSocket连接已关闭")
    
    # ==================== 客户管理处理方法 ====================
    
    async def _handle_get_customers(self, message: dict, websocket: WebSocket):
        """处理获取客户列表消息"""
        try:
            customers = self.db_manager.get_all_customers()
            await self._send_message(websocket, {
                'type': 'customers_received',
                'customers': customers
            })
            print(f"📋 发送客户列表: {len(customers)} 个客户")
        except Exception as e:
            print(f"❌ 获取客户列表失败: {e}")
            await self._send_error(websocket, f'获取客户列表失败: {str(e)}')
    
    async def _handle_create_customer(self, message: dict, websocket: WebSocket):
        """处理创建客户消息"""
        try:
            customer_data = message.get('data', {})
            customer = self.db_manager.create_customer(customer_data)
            
            # 广播新客户给所有客户端
            await self._broadcast_message({
                'type': 'customer_created',
                'customer': customer
            })
            
            print(f"✅ 创建客户成功: {customer['name']}")
        except Exception as e:
            print(f"❌ 创建客户失败: {e}")
            await self._send_error(websocket, f'创建客户失败: {str(e)}')
    
    async def _handle_batch_create_customers(self, message: dict, websocket: WebSocket):
        """处理批量创建客户消息"""
        try:
            customers_data = message.get('data', [])
            created_customers = self.db_manager.batch_create_customers(customers_data)
            
            # 广播所有新客户给所有客户端
            await self._broadcast_message({
                'type': 'customers_batch_created',
                'customers': created_customers
            })
            
            print(f"✅ 批量创建客户成功: {len(created_customers)} 个客户")
        except Exception as e:
            print(f"❌ 批量创建客户失败: {e}")
            await self._send_error(websocket, f'批量创建客户失败: {str(e)}')
    
    async def _handle_update_customer(self, message: dict, websocket: WebSocket):
        """处理更新客户消息"""
        try:
            customer_data = message.get('data', {})
            customer_id = customer_data.get('id')
            
            if not customer_id:
                await self._send_error(websocket, '缺少客户ID')
                return
            
            customer = self.db_manager.update_customer(customer_id, customer_data)
            if customer:
                # 广播更新给所有客户端
                await self._broadcast_message({
                    'type': 'customer_updated',
                    'customer': customer
                })
                print(f"✅ 更新客户成功: {customer['name']}")
            else:
                await self._send_error(websocket, '客户不存在')
        except Exception as e:
            print(f"❌ 更新客户失败: {e}")
            await self._send_error(websocket, f'更新客户失败: {str(e)}')
    
    async def _handle_delete_customer(self, message: dict, websocket: WebSocket):
        """处理删除客户消息"""
        try:
            customer_id = message.get('customer_id')
            
            if not customer_id:
                await self._send_error(websocket, '缺少客户ID')
                return
            
            success = self.db_manager.delete_customer(customer_id)
            if success:
                # 广播删除给所有客户端
                await self._broadcast_message({
                    'type': 'customer_deleted',
                    'customer_id': customer_id
                })
                print(f"✅ 删除客户成功: ID {customer_id}")
            else:
                await self._send_error(websocket, '客户不存在')
        except Exception as e:
            print(f"❌ 删除客户失败: {e}")
            await self._send_error(websocket, f'删除客户失败: {str(e)}')
    
